import Vue from 'vue';
import { Toast } from 'vant';
import Clipboard from 'clipboard';
import baiduPush from '../utils/baiduStatistics';
import customDialog from '../components/staticComponent/custom-dialog/index';
let setTimerOut = '';

function toastCheck(toast, type) {
	if (type == 1) {
		customDialog();
	} else {
		Toast(toast);
	}
}

function copyboard(toast = '复制成功', type = '') {
	const clipboard = new Clipboard('._copy-btn');

	clipboard.on('success', e => {
		if (!setTimerOut) {
			setTimerOut = setTimeout(() => {
				toastCheck(toast, type);
			}, 200);
		} else {
			clearTimeout(setTimerOut);
			setTimerOut = setTimeout(() => {
				toastCheck(toast, type);
			}, 200);
		}
		e.clearSelection();
	});

	clipboard.on('error', err => {
		console.error(err);
		Toast('复制失败');
	});
}

Vue.directive('copy', {
	bind: (el, binding) => {
		copyboard(binding.value.toast, binding.value.type);
		el.addEventListener('click', () => {
			if (binding.value.toast) {
				baiduPush('复制事件', 'tap', binding.value.toast);
			}
			if (binding.value.length > 100) {
				baiduPush('复制事件', 'tap', '复制商品文案');
			}
		});
	},
	inserted: (el, binding) => {
		el.className = el.className + ' _copy-btn';
		el.setAttribute('data-clipboard-text', typeof binding.value == 'string' ? binding.value : binding.value.value);
	},
	update: (el, binding) => {
		el.setAttribute('data-clipboard-text', typeof binding.value == 'string' ? binding.value : binding.value.value);
	}
});
